/*******************************************************************************
 * Copyright (c) 2011 Irineu Martins de Lima Moura (imlm2).
 * This file is part of JBeat.
 * 
 *     JBeat is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU Lesser General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 * 
 *     JBeat is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU Lesser General Public License for more details.
 * 
 *     You should have received a copy of the GNU Lesser General Public License
 *     along with JBeat.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * Contributors:
 *     Irineu Martins de Lima Moura (imlm2) - initial API and implementation
 ******************************************************************************/
package br.ufpe.cin.imlm2.jbeat.soot.traps;

import java.util.Iterator;

import soot.Body;
import soot.SootMethod;
import soot.Trap;
import soot.jimple.NopStmt;
import soot.jimple.toolkits.scalar.NopEliminator;
import soot.tagkit.Host;
import soot.util.Chain;
import br.ufpe.cin.imlm2.jbeat.soot.common.MethodTagger;

/**
 * Removes empty traps or 'nop' instructions!
 * Doesn't really do any tagging...
 * 
 * @author Irineu
 */
public class EmptyTrapRemover extends MethodTagger {

	private void removeEmptyTraps( Body b ) {
		Chain<Trap> traps = b.getTraps();
		Iterator<Trap> trapsIt = traps.snapshotIterator();
		boolean hasNops = false;
		while ( trapsIt.hasNext() ) {
			Trap next = trapsIt.next();
			if ( next.getBeginUnit().equals( next.getEndUnit() ) ) {
				traps.remove( next );
			}
			if ( next.getHandlerUnit() instanceof NopStmt )
				hasNops = true;
		}
		if ( hasNops )
			NopEliminator.v().transform( b );
	}

	@Override
	protected void tag() {
		super.tag();
		for ( Host h : this.getTargetSet() ) {
			SootMethod meth = (SootMethod) h;
			this.removeEmptyTraps( meth.retrieveActiveBody() );
		}
	}

	@Override
	protected void checkTags( SootMethod m ) {
		// Empty.
	}

}
